/*!
 * \file test_threadpool_comprehensive.cpp
 * \project WonderTrader
 *
 * \author AI Assistant
 * \date 2024/12/19
 * 
 * \brief 线程池综合测试文件
 * 测试线程池的各种功能和性能特征
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <string>
#include <vector>
#include <thread>
#include <chrono>
#include <atomic>
#include <future>
#include <functional>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <random>

// 简单的线程池实现用于测试
class SimpleThreadPool {
public:
    explicit SimpleThreadPool(size_t num_threads) : stop_(false) {
        for (size_t i = 0; i < num_threads; ++i) {
            workers_.emplace_back([this] {
                while (true) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(queue_mutex_);
                        condition_.wait(lock, [this] { return stop_ || !tasks_.empty(); });
                        
                        if (stop_ && tasks_.empty()) {
                            return;
                        }
                        
                        task = std::move(tasks_.front());
                        tasks_.pop();
                    }
                    task();
                }
            });
        }
    }
    
    ~SimpleThreadPool() {
        {
            std::unique_lock<std::mutex> lock(queue_mutex_);
            stop_ = true;
        }
        condition_.notify_all();
        
        for (std::thread& worker : workers_) {
            worker.join();
        }
    }
    
    template<class F, class... Args>
    auto enqueue(F&& f, Args&&... args) -> std::future<typename std::invoke_result<F, Args...>::type> {
        using return_type = typename std::invoke_result<F, Args...>::type;
        
        auto task = std::make_shared<std::packaged_task<return_type()>>(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );
        
        std::future<return_type> res = task->get_future();
        {
            std::unique_lock<std::mutex> lock(queue_mutex_);
            
            if (stop_) {
                throw std::runtime_error("enqueue on stopped ThreadPool");
            }
            
            tasks_.emplace([task]() { (*task)(); });
        }
        condition_.notify_one();
        return res;
    }
    
    size_t size() const { return workers_.size(); }
    
    size_t pending_tasks() const {
        std::unique_lock<std::mutex> lock(queue_mutex_);
        return tasks_.size();
    }

private:
    std::vector<std::thread> workers_;
    std::queue<std::function<void()>> tasks_;
    mutable std::mutex queue_mutex_;
    std::condition_variable condition_;
    bool stop_;
};

/**
 * 线程池综合测试类
 * 测试线程池的各种功能和性能特征
 */
class ThreadPoolComprehensiveTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 初始化测试环境
        default_thread_count_ = std::thread::hardware_concurrency();
        if (default_thread_count_ == 0) {
            default_thread_count_ = 4; // 默认4个线程
        }
        
        test_task_count_ = 100;
        heavy_task_count_ = 10;
    }

    void TearDown() override {
        // 清理测试环境
    }

    size_t default_thread_count_;
    int test_task_count_;
    int heavy_task_count_;
};

/**
 * 测试基本的线程池创建和销毁
 */
TEST_F(ThreadPoolComprehensiveTest, TestBasicCreationAndDestruction) {
    // 测试创建线程池
    {
        SimpleThreadPool pool(4);
        EXPECT_EQ(pool.size(), 4);
    }
    
    // 测试不同大小的线程池
    {
        SimpleThreadPool small_pool(1);
        EXPECT_EQ(small_pool.size(), 1);
    }
    
    {
        SimpleThreadPool large_pool(16);
        EXPECT_EQ(large_pool.size(), 16);
    }
    
    // 测试零线程池（边界条件）
    {
        SimpleThreadPool zero_pool(0);
        EXPECT_EQ(zero_pool.size(), 0);
    }
}

/**
 * 测试基本任务执行
 */
TEST_F(ThreadPoolComprehensiveTest, TestBasicTaskExecution) {
    SimpleThreadPool pool(4);
    std::atomic<int> counter(0);
    
    // 提交简单任务
    auto future = pool.enqueue([&counter]() {
        counter.fetch_add(1);
        return 42;
    });
    
    // 等待任务完成
    int result = future.get();
    EXPECT_EQ(result, 42);
    EXPECT_EQ(counter.load(), 1);
}

/**
 * 测试多任务并发执行
 */
TEST_F(ThreadPoolComprehensiveTest, TestMultipleTaskExecution) {
    SimpleThreadPool pool(4);
    std::atomic<int> counter(0);
    std::vector<std::future<void>> futures;
    
    // 提交多个任务
    for (int i = 0; i < test_task_count_; ++i) {
        futures.push_back(pool.enqueue([&counter, i]() {
            counter.fetch_add(1);
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
        }));
    }
    
    // 等待所有任务完成
    for (auto& future : futures) {
        future.get();
    }
    
    EXPECT_EQ(counter.load(), test_task_count_);
}

/**
 * 测试任务返回值
 */
TEST_F(ThreadPoolComprehensiveTest, TestTaskReturnValues) {
    SimpleThreadPool pool(4);
    std::vector<std::future<int>> futures;
    
    // 提交返回不同值的任务
    for (int i = 0; i < 10; ++i) {
        futures.push_back(pool.enqueue([i]() {
            return i * i;
        }));
    }
    
    // 验证返回值
    for (int i = 0; i < 10; ++i) {
        int result = futures[i].get();
        EXPECT_EQ(result, i * i);
    }
}

/**
 * 测试任务参数传递
 */
TEST_F(ThreadPoolComprehensiveTest, TestTaskParameters) {
    SimpleThreadPool pool(4);
    
    // 测试多参数任务
    auto future1 = pool.enqueue([](int a, int b, int c) {
        return a + b + c;
    }, 1, 2, 3);
    
    EXPECT_EQ(future1.get(), 6);
    
    // 测试字符串参数
    auto future2 = pool.enqueue([](const std::string& str, int count) {
        std::string result;
        for (int i = 0; i < count; ++i) {
            result += str;
        }
        return result;
    }, "hello", 3);
    
    EXPECT_EQ(future2.get(), "hellohellohello");
}

/**
 * 测试异常处理
 */
TEST_F(ThreadPoolComprehensiveTest, TestExceptionHandling) {
    SimpleThreadPool pool(4);
    
    // 提交会抛出异常的任务
    auto future = pool.enqueue([]() {
        throw std::runtime_error("测试异常");
        return 42;
    });
    
    // 验证异常被正确传播
    try {
        future.get();
        FAIL() << "应该抛出异常";
    } catch (const std::runtime_error& e) {
        EXPECT_STREQ(e.what(), "测试异常");
    }
}

/**
 * 测试线程池负载均衡
 */
TEST_F(ThreadPoolComprehensiveTest, TestLoadBalancing) {
    const int num_threads = 4;
    SimpleThreadPool pool(num_threads);
    
    std::vector<std::atomic<int>> thread_counters(num_threads);
    for (auto& counter : thread_counters) {
        counter.store(0);
    }
    
    std::mutex thread_id_mutex;
    std::map<std::thread::id, int> thread_id_map;
    int next_id = 0;
    
    std::vector<std::future<void>> futures;
    
    // 提交大量任务
    for (int i = 0; i < test_task_count_; ++i) {
        futures.push_back(pool.enqueue([&thread_counters, &thread_id_mutex, &thread_id_map, &next_id]() {
            std::thread::id current_id = std::this_thread::get_id();
            int thread_index;
            
            {
                std::lock_guard<std::mutex> lock(thread_id_mutex);
                if (thread_id_map.find(current_id) == thread_id_map.end()) {
                    thread_id_map[current_id] = next_id++;
                }
                thread_index = thread_id_map[current_id];
            }
            
            if (thread_index < static_cast<int>(thread_counters.size())) {
                thread_counters[thread_index].fetch_add(1);
            }
            
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }));
    }
    
    // 等待所有任务完成
    for (auto& future : futures) {
        future.get();
    }
    
    // 验证负载分布
    int total_tasks = 0;
    for (const auto& counter : thread_counters) {
        int count = counter.load();
        total_tasks += count;
        std::cout << "线程执行任务数: " << count << std::endl;
    }
    
    EXPECT_EQ(total_tasks, test_task_count_);
    
    // 验证负载相对均衡（允许一定的偏差）
    int average = test_task_count_ / num_threads;
    for (const auto& counter : thread_counters) {
        int count = counter.load();
        if (count > 0) { // 只检查实际使用的线程
            EXPECT_GE(count, average / 2);
            EXPECT_LE(count, average * 2);
        }
    }
}

/**
 * 测试重任务处理
 */
TEST_F(ThreadPoolComprehensiveTest, TestHeavyTaskProcessing) {
    SimpleThreadPool pool(4);
    std::vector<std::future<long long>> futures;
    
    // 减少任务复杂度和数量以避免超时
    const int reduced_task_count = 5; // 减少任务数量
    
    // 提交计算密集型任务
    for (int i = 0; i < reduced_task_count; ++i) {
        futures.push_back(pool.enqueue([i]() {
            // 计算斐波那契数列（递归版本，计算密集）
            std::function<long long(int)> fibonacci = [&fibonacci](int n) -> long long {
                if (n <= 1) return n;
                return fibonacci(n - 1) + fibonacci(n - 2);
            };
            
            return fibonacci(25 + i); // 减少计算复杂度：从30+i改为25+i
        }));
    }
    
    auto start = std::chrono::high_resolution_clock::now();
    
    // 等待所有重任务完成，添加超时机制
    std::vector<long long> results;
    for (auto& future : futures) {
        // 每个任务最多等待600ms
        auto status = future.wait_for(std::chrono::milliseconds(600));
        if (status == std::future_status::ready) {
            results.push_back(future.get());
        } else {
            FAIL() << "Heavy task timed out after 600ms";
        }
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    // 验证结果
    EXPECT_EQ(results.size(), reduced_task_count);
    for (long long result : results) {
        EXPECT_GT(result, 0);
    }
    
    std::cout << "重任务处理耗时: " << duration.count() << " 毫秒" << std::endl;
    EXPECT_LT(duration.count(), 2500) << "重任务处理应在2.5秒内完成";
}

/**
 * 测试线程池性能特征
 */
TEST_F(ThreadPoolComprehensiveTest, TestPerformanceCharacteristics) {
    const int task_count = 1000;
    
    // 测试单线程性能
    auto start_single = std::chrono::high_resolution_clock::now();
    {
        SimpleThreadPool single_pool(1);
        std::vector<std::future<int>> futures;
        
        for (int i = 0; i < task_count; ++i) {
            futures.push_back(single_pool.enqueue([i]() {
                return i * 2;
            }));
        }
        
        for (auto& future : futures) {
            future.get();
        }
    }
    auto end_single = std::chrono::high_resolution_clock::now();
    auto single_duration = std::chrono::duration_cast<std::chrono::microseconds>(end_single - start_single);
    
    // 测试多线程性能
    auto start_multi = std::chrono::high_resolution_clock::now();
    {
        SimpleThreadPool multi_pool(4);
        std::vector<std::future<int>> futures;
        
        for (int i = 0; i < task_count; ++i) {
            futures.push_back(multi_pool.enqueue([i]() {
                return i * 2;
            }));
        }
        
        for (auto& future : futures) {
            future.get();
        }
    }
    auto end_multi = std::chrono::high_resolution_clock::now();
    auto multi_duration = std::chrono::duration_cast<std::chrono::microseconds>(end_multi - start_multi);
    
    std::cout << "单线程执行 " << task_count << " 个任务耗时: " 
              << single_duration.count() << " 微秒" << std::endl;
    std::cout << "多线程执行 " << task_count << " 个任务耗时: " 
              << multi_duration.count() << " 微秒" << std::endl;
    
    // 多线程应该比单线程快（在有足够任务的情况下）
    // 但由于任务很简单，可能看不到明显差异
    EXPECT_GT(single_duration.count(), 0);
    EXPECT_GT(multi_duration.count(), 0);
}

/**
 * 测试任务队列管理
 */
TEST_F(ThreadPoolComprehensiveTest, TestTaskQueueManagement) {
    SimpleThreadPool pool(2); // 使用较少的线程来测试队列
    std::atomic<int> started_tasks(0);
    std::atomic<int> completed_tasks(0);
    
    // 提交大量任务，超过线程数
    std::vector<std::future<void>> futures;
    for (int i = 0; i < 20; ++i) {
        futures.push_back(pool.enqueue([&started_tasks, &completed_tasks, i]() {
            started_tasks.fetch_add(1);
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
            completed_tasks.fetch_add(1);
        }));
    }
    
    // 短暂等待，检查任务是否在队列中等待
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
    
    int started = started_tasks.load();
    int completed = completed_tasks.load();
    
    // 应该有任务已经开始但还没有全部完成
    EXPECT_GT(started, 0);
    EXPECT_LT(completed, 20);
    
    // 等待所有任务完成
    for (auto& future : futures) {
        future.get();
    }
    
    EXPECT_EQ(completed_tasks.load(), 20);
}

/**
 * 测试线程池资源管理
 */
TEST_F(ThreadPoolComprehensiveTest, TestResourceManagement) {
    std::atomic<int> destructor_count(0);
    
    // 创建带有资源的任务
    {
        SimpleThreadPool pool(4);
        std::vector<std::future<void>> futures;
        
        for (int i = 0; i < 10; ++i) {
            futures.push_back(pool.enqueue([&destructor_count]() {
                // 创建一个会在析构时增加计数器的对象
                struct TestResource {
                    std::atomic<int>* counter;
                    TestResource(std::atomic<int>* c) : counter(c) {}
                    ~TestResource() { counter->fetch_add(1); }
                };
                
                TestResource resource(&destructor_count);
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }));
        }
        
        // 等待所有任务完成
        for (auto& future : futures) {
            future.get();
        }
    } // 线程池析构
    
    // 验证所有资源都被正确释放
    EXPECT_EQ(destructor_count.load(), 10);
}

/**
 * 测试线程池停止后的行为
 */
TEST_F(ThreadPoolComprehensiveTest, TestStoppedPoolBehavior) {
    auto pool = std::make_unique<SimpleThreadPool>(4);
    
    // 提交一些任务
    std::vector<std::future<int>> futures;
    for (int i = 0; i < 5; ++i) {
        futures.push_back(pool->enqueue([i]() {
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            return i;
        }));
    }
    
    // 销毁线程池
    pool.reset();
    
    // 验证已提交的任务仍然可以完成
    for (int i = 0; i < 5; ++i) {
        int result = futures[i].get();
        EXPECT_EQ(result, i);
    }
}

/**
 * 测试并发任务提交
 */
TEST_F(ThreadPoolComprehensiveTest, TestConcurrentTaskSubmission) {
    SimpleThreadPool pool(4);
    std::atomic<int> task_counter(0);
    std::vector<std::thread> submitter_threads;
    std::vector<std::vector<std::future<void>>> all_futures(4);
    
    // 多个线程同时提交任务
    for (int t = 0; t < 4; ++t) {
        submitter_threads.emplace_back([&pool, &task_counter, &all_futures, t]() {
            for (int i = 0; i < 25; ++i) {
                all_futures[t].push_back(pool.enqueue([&task_counter]() {
                    task_counter.fetch_add(1);
                    std::this_thread::sleep_for(std::chrono::milliseconds(1));
                }));
            }
        });
    }
    
    // 等待所有提交线程完成
    for (auto& thread : submitter_threads) {
        thread.join();
    }
    
    // 等待所有任务完成
    for (auto& futures : all_futures) {
        for (auto& future : futures) {
            future.get();
        }
    }
    
    EXPECT_EQ(task_counter.load(), 100);
}

/**
 * 测试任务优先级（简单版本）
 */
TEST_F(ThreadPoolComprehensiveTest, TestTaskOrdering) {
    SimpleThreadPool pool(1); // 单线程确保顺序
    std::vector<int> execution_order;
    std::mutex order_mutex;
    
    std::vector<std::future<void>> futures;
    
    // 提交有序任务
    for (int i = 0; i < 10; ++i) {
        futures.push_back(pool.enqueue([&execution_order, &order_mutex, i]() {
            std::lock_guard<std::mutex> lock(order_mutex);
            execution_order.push_back(i);
        }));
    }
    
    // 等待所有任务完成
    for (auto& future : futures) {
        future.get();
    }
    
    // 验证执行顺序（FIFO）
    EXPECT_EQ(execution_order.size(), 10);
    for (int i = 0; i < 10; ++i) {
        EXPECT_EQ(execution_order[i], i);
    }
}

/**
 * 测试线程池压力测试
 */
TEST_F(ThreadPoolComprehensiveTest, TestStressTest) {
    const int stress_task_count = 10000;
    SimpleThreadPool pool(8);
    
    std::atomic<int> completed_count(0);
    std::atomic<long long> sum(0);
    
    auto start = std::chrono::high_resolution_clock::now();
    
    std::vector<std::future<void>> futures;
    
    // 提交大量任务
    for (int i = 0; i < stress_task_count; ++i) {
        futures.push_back(pool.enqueue([&completed_count, &sum, i]() {
            // 执行一些计算
            long long local_sum = 0;
            for (int j = 0; j < 100; ++j) {
                local_sum += i * j;
            }
            sum.fetch_add(local_sum);
            completed_count.fetch_add(1);
        }));
    }
    
    // 等待所有任务完成
    for (auto& future : futures) {
        future.get();
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    // 验证结果
    EXPECT_EQ(completed_count.load(), stress_task_count);
    EXPECT_GT(sum.load(), 0);
    
    std::cout << "压力测试: " << stress_task_count << " 个任务耗时 " 
              << duration.count() << " 毫秒" << std::endl;
    std::cout << "平均每个任务耗时: " 
              << static_cast<double>(duration.count()) / stress_task_count << " 毫秒" << std::endl;
}

/**
 * 测试完整的线程池工作流程
 */
TEST_F(ThreadPoolComprehensiveTest, TestCompleteWorkflow) {
    // 模拟完整的线程池使用场景
    
    // 1. 创建线程池
    SimpleThreadPool pool(default_thread_count_);
    EXPECT_EQ(pool.size(), default_thread_count_);
    
    // 2. 提交不同类型的任务
    std::vector<std::future<std::string>> string_futures;
    std::vector<std::future<int>> int_futures;
    std::vector<std::future<void>> void_futures;
    
    // 字符串处理任务
    for (int i = 0; i < 5; ++i) {
        string_futures.push_back(pool.enqueue([i]() {
            return "Task " + std::to_string(i) + " completed";
        }));
    }
    
    // 数值计算任务
    for (int i = 0; i < 5; ++i) {
        int_futures.push_back(pool.enqueue([i]() {
            int result = 1;
            for (int j = 1; j <= i; ++j) {
                result *= j;
            }
            return result; // 计算阶乘
        }));
    }
    
    // 无返回值任务
    std::atomic<int> void_task_count(0);
    for (int i = 0; i < 5; ++i) {
        void_futures.push_back(pool.enqueue([&void_task_count]() {
            void_task_count.fetch_add(1);
        }));
    }
    
    // 3. 收集结果
    std::vector<std::string> string_results;
    for (auto& future : string_futures) {
        string_results.push_back(future.get());
    }
    
    std::vector<int> int_results;
    for (auto& future : int_futures) {
        int_results.push_back(future.get());
    }
    
    for (auto& future : void_futures) {
        future.get();
    }
    
    // 4. 验证结果
    EXPECT_EQ(string_results.size(), 5);
    EXPECT_EQ(int_results.size(), 5);
    EXPECT_EQ(void_task_count.load(), 5);
    
    // 验证字符串结果
    for (int i = 0; i < 5; ++i) {
        std::string expected = "Task " + std::to_string(i) + " completed";
        EXPECT_EQ(string_results[i], expected);
    }
    
    // 验证阶乘结果
    std::vector<int> expected_factorials = {1, 1, 2, 6, 24}; // 0!, 1!, 2!, 3!, 4!
    for (int i = 0; i < 5; ++i) {
        EXPECT_EQ(int_results[i], expected_factorials[i]);
    }
    
    std::cout << "完整工作流程测试完成:" << std::endl;
    std::cout << "- 处理了 " << string_results.size() << " 个字符串任务" << std::endl;
    std::cout << "- 处理了 " << int_results.size() << " 个计算任务" << std::endl;
    std::cout << "- 处理了 " << void_task_count.load() << " 个无返回值任务" << std::endl;
} 